import 'package:base_moudle/index.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../../../../models/data_model/HyWorkModel.dart';
import '../../../../new_paltform/define/hy_header.dart';
import '../../db/work_app_model.dart';
import '../../setting/work_setting.dart';
import '../drawer/hy_work_store_drawer_page.dart';
import '../hy_work_home_logic.dart';
import '../my_work/hy_me_work_logic.dart';
import 'hy_add_search_page.dart';

class HYAddOftenUsedPage extends StatefulWidget {
  static Future? push({int code = 1}) {
    return Get.to(() =>
        HYAddOftenUsedPage(
          code: code,
        ));
  }

  HYAddOftenUsedPage({this.code = 1});

  int code;

  @override
  State<StatefulWidget> createState() {
    return _HYAddOftenUsedPageState();
  }
}

class _HYAddOftenUsedPageState extends State<HYAddOftenUsedPage>
    with SingleTickerProviderStateMixin {
  late List<String> appsTypes;

  HyHomeGetxController get controller {
    if (widget.code == 2) {
      HyMeWorkHomeLogic _controller = Get.find();
      return _controller;
    } else {
      HyWorkHomeLogic _controller = Get.find();
      return _controller;
    }
  }

  late TabController _tabController;

  @override
  void initState() {
    if (widget.code == 2) {
      appsTypes = ItemModel.myAppTypes();
    } else {
      appsTypes = ItemModel.appTypes();
    }
    super.initState();

    _tabController = TabController(vsync: this, length: appsTypes.length);
  }

  @override
  Widget build(BuildContext context) {
    return PageViewBase(
      appBar: AppBar(
        title: const Text(
          '添加常用',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        ),
        shadowColor: Colors.transparent,
        actions: <Widget>[
          HYContainer(
            padding: const EdgeInsets.all(15),
            child: Image.asset(
              'assets/images/homeIcons/home_search.png',
              width: 24,
              height: 24,
            ),
            onTap: () {
              HYAddSearchPage.push()?.then((dynamic value) {
                controller.onItemList();
                setState(() {});
              });
            },
          ),
        ],
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(200),
          child: Container(
            color: zs_color_f2,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                haveBeenAdded(),
                allApplyTabbar(),
              ],
            ),
          ),
        ),
      ),
      body: Obx(() =>
          TabBarView(
            // key: bKey,
            controller: _tabController,
            children: appsTypes.map((String e) => _buildTabbarView(e)).toList(),
          )),
    );
  }

  //注释:选择的显示样式
  Widget haveBeenAdded() {
    return Container(
      color: Colors.white,
      height: 64,
      padding: const EdgeInsets.only(bottom: 14),
      child: Row(
        children: <Widget>[
          Obx(() {
            return Container(
              padding: const EdgeInsets.only(
                left: 16,
                top: 16,
                bottom: 16,
                right: 12,
              ),
              child: Text(
                '已添加 (${controller.itemList.length}) ',
                style: TextStyle(fontSize: 12, color: zs_black_333),
              ),
            );
          }),
          Expanded(
            child: Obx(() {
              return ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  double wh = 32;
                  return HYContainer(
                    margin: const EdgeInsets.only(top: 4, bottom: 4, right: 4),
                    height: wh,
                    width: wh,
                    child: controller.itemList[index].iconName.contains('http')
                        ? CachedNetworkImage(
                      imageUrl: controller.itemList[index].iconName,
                      width: wh,
                      height: wh,
                      errorWidget: (BuildContext c, String s, i) {
                        return Container(
                          // margin: EdgeInsets.all(15),
                          width: wh, height: wh,
                          decoration: BoxDecoration(
                              color: zs_color_f2,
                              borderRadius: BorderRadius.circular(6)),
                        );
                      },
                    )
                        : Image.asset(
                      controller.itemList[index].iconName,
                      width: wh,
                      height: wh,
                    ),
                  );
                },
                scrollDirection: Axis.horizontal,
                itemCount: controller.itemList.length,
              );
            }),
          ),
          HYContainer(
            padding: const EdgeInsets.only(
              left: 30,
              top: 16,
              bottom: 16,
              right: 16,
            ),
            child: Text(
              '设置',
              style: TextStyle(fontSize: 12, color: ColorHex('#FF6C06')),
            ),
            onTap: () {
              HyWorkSettingPage.push(controller.itemList)?.then((value) {
                if (value is List<ItemModel>) {
                  controller.itemList.value = value;
                  if (widget.code == 2) {
                    (controller as HyMeWorkHomeLogic).onUpdateLike();
                  } else {
                    (controller as HyWorkHomeLogic).onUpdateLike();
                  }
                }
              });
            },
          ),
        ],
      ),
    );
  }

  //注释:全部的应用
  Widget allApplyTabbar() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          color: Colors.white,
          margin: const EdgeInsets.only(top: 12),
          padding: const EdgeInsets.only(
            left: 16,
            top: 20,
            bottom: 15,
            right: 16,
          ),
          child: Row(
            children: <Widget>[
              Text(
                '全部应用',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: zs_black_333,
                ),
              ),
            ],
          ),
        ),
        Container(
          margin: const EdgeInsets.only(bottom: 2),
          color: Colors.white,
          child: DefaultTabController(
            length: appsTypes.length,
            child: HYContainer(
                alignment: Alignment.centerLeft,
                padding: const EdgeInsets.only(right: 16),
                child: Stack(
                  alignment: Alignment.centerLeft,
                  children: <Widget>[
                    TabBar(
                      labelColor: zs_mainColor,
                      labelStyle: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                      labelPadding: const EdgeInsets.only(left: 16, right: 10),
                      unselectedLabelColor: zs_black_999,
                      indicatorSize: TabBarIndicatorSize.label,
                      indicatorColor: zs_mainColor,
                      isScrollable: true,
                      controller: _tabController,
                      tabs: appsTypes
                          .map((String e) =>
                          Tab(
                            text: e,
                          ))
                          .toList(),
                    ).marginOnly(right: 50),
                    if (appsTypes.length > 4)
                      Align(
                        alignment: Alignment.centerRight,
                        child: HYContainer(
                          onTap: () {
                            HyWorkStoreDrawerPage.push(
                                arr: appsTypes, context: context)
                                ?.then((String? value) {
                              if (value != null) {
                                final int selectIndex =
                                appsTypes.indexOf(value);
                                _tabController.animateTo(selectIndex);
                              }
                            });
                          },
                          child: const Icon(Icons.dehaze),
                        ),
                      ),
                  ],
                )),
          ),
        ),
      ],
    );
  }

  Widget _buildTabbarView(String str) {
    List<Rx<ItemModel>> list = [];
    if (str == '最近使用') {
      list = List<ItemModel>.from(controller.timeList.value)
          .map((e) => e.obs)
          .toList();
    } else if (str == '办公工作') {
      list = List<ItemModel>.from(controller.allList
          .where(
              (ItemModel element) => ['办公工作', 'web'].contains(element.type))
          .toList())
          .map((e) => e.obs)
          .toList();
    } else if (str == '全部应用') {
      list =
          List<ItemModel>.from(controller.allList).map((e) => e.obs).toList();
    } else {
      list = List<ItemModel>.from(controller.allList
          .where((ItemModel element) => element.type == str)
          .toList())
          .map((e) => e.obs)
          .toList();
    }
    return HYAllApplyList(
      list: list,
      title: str,
      code: widget.code,
    );
  }
}

class HYAllApplyList extends StatefulWidget {
  HYAllApplyList(
      {Key? key, required this.list, required this.title, this.code = 1})
      : super(key: key);
  List<Rx<ItemModel>> list;
  String title;
  int code;

  @override
  State<StatefulWidget> createState() {
    return _HYAllApplyListState();
  }
}

class _HYAllApplyListState extends State<HYAllApplyList>
    with SingleTickerProviderStateMixin {
  HyHomeGetxController get controller {
    if (widget.code == 2) {
      HyMeWorkHomeLogic _controller = Get.find();
      return _controller;
    } else {
      HyWorkHomeLogic _controller = Get.find();
      return _controller;
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      shrinkWrap: true,
      itemCount: widget.list.isNotEmpty ? widget.list.length : 1,
      itemBuilder: (BuildContext context, int index) {
        if (widget.list.isNotEmpty) {
          return allApplyWidget(model: widget.list[index], index: index);
        } else {
          return Container(
            margin: const EdgeInsets.only(top: 40),
            child: Column(
              children: <Widget>[
                Stack(
                  alignment: Alignment.bottomCenter,
                  children: <Widget>[
                    Image.asset(
                      'assets/images/empty_data.png',
                      width: Get.width - 80,
                      fit: BoxFit.cover,
                    ),
                    Container(
                      margin: const EdgeInsets.only(bottom: 40),
                      child: Text(
                        '暂无数据',
                        style: TextStyle(color: zs_black_999, fontSize: 16),
                      ),
                    ),
                  ],
                )
              ],
            ),
          );
        }
      },
    );
  }

  Widget allApplyWidget({required Rx<ItemModel> model, int? index}) {
    return Container(
      padding: EdgeInsets.only(
          left: 15, top: index == 0 ? 30 : 15, bottom: 15, right: 15),
      child: Row(
        children: <Widget>[
          if (model.value.iconName.contains('http'))
            CachedNetworkImage(
              imageUrl: model.value.iconName,
              width: 50,
              height: 50,
              fit: BoxFit.cover,
              errorWidget: (BuildContext c, String s, i) {
                return Container(
                  // margin: EdgeInsets.all(15),
                  width: 50, height: 50,
                  decoration: BoxDecoration(
                      color: zs_color_f2,
                      borderRadius: BorderRadius.circular(8)),
                );
              },
            )
          else
            Image.asset(
              model.value.iconName,
              width: 50,
              height: 50,
            ),
          Expanded(
            child: Container(
              margin: const EdgeInsets.only(left: 16, right: 16),
              child: Text(
                model.value.title,
                style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.bold,
                  color: zs_black_333,
                ),
              ),
            ),
          ),
          HYContainer(
            width: 56,
            height: 30,
            alignment: Alignment.center,
            borderRadius: const BorderRadius.all(Radius.circular(6)),
            border: Border.all(
              color: model.value.isDisplay == true
                  ? Colors.transparent
                  : ColorHex('#187AFF'),
            ),
            child: Text(
              model.value.isDisplay == true ? '已添加' : '添加',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                color: model.value.isDisplay == true
                    ? zs_color_ccc
                    : ColorHex('#187AFF'),
              ),
            ),
            onTap: () async {
              if (model.value.isDisplay == false) {
                int rank = controller.itemList.length + 1;
                await HyWorkAppModel.saveAddLikeModel(
                  model: model.value,
                  rank: rank,
                  code: widget.code,
                ).whenComplete(() => EasyLoading.showToast('添加成功'));
                model.value.isDisplay = true;
                if (widget.code == 2) {
                  (controller as HyMeWorkHomeLogic).onItemList();
                } else {
                  (controller as HyWorkHomeLogic).onItemList();
                }
                setState(() {});
              }
            },
          ),
        ],
      ),
    );
  }
}
